<template>
  <div class="dashboard-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            class="!w-[240px]"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="类型" prop="hy3">
          <el-select
            v-model="queryParams.projectType"
            placeholder="类型"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery()"
          >
            <el-option label="油田" value="油田" />
            <el-option label="气田" value="气田" />
            <el-option label="油气田" value="油气田" />
          </el-select>
        </el-form-item>
        <el-form-item label="海域" prop="hy3">
          <el-select
            v-model="queryParams.hy3"
            placeholder="海域"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery()"
          >
            <el-option label="渤海" value="渤海" />
            <el-option label="东海" value="东海" />
            <el-option label="南海东部" value="南海东部" />
            <el-option label="南海西部(海南)" value="南海西部(海南)" />
            <el-option label="南海西部(湛江)" value="南海西部(湛江)" />
          </el-select>
        </el-form-item>
        <el-form-item label="平均水深" prop="pjss7">
          <el-select
            v-model="queryParams.pjss7"
            placeholder="平均水深"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery()"
          >
            <el-option label="<50m" value="1" />
            <el-option label="50m-100m" value="2" />
            <el-option label="100m-300m" value="3" />
            <el-option label="300m-1500m" value="4" />
            <el-option label=">=1500m" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="高峰产能" prop="gfcn3">
          <el-select
            v-model="queryParams.gfcn3"
            placeholder="高峰产能"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery()"
          >
            <el-option label="<50万吨" value="1" />
            <el-option label="50-100万吨" value="2" />
            <el-option label="100-200万吨" value="3" />
            <el-option label="200-300万吨" value="4" />
            <el-option label=">=300万吨" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="xmmc1">
          <el-input
            v-model="queryParams.xmmc1"
            placeholder="项目名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 预警模块 -->
    <el-card shadow="never" class="warning-module-card mt-5">
      <div slot="header" class="flex-x-between">
        <span class="module-title">预警模块</span>
      </div>

      <!-- 三个卡片 -->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-card shadow="never">
            <template #header>
              <div class="flex-x-between">
                <span class="text-gray">原油采收率</span>
              </div>
            </template>
            <div v-if="yyList.length > 0">
              <el-table :data="yyList" style="width: 100%" :show-header="false">
                <el-table-column label="排名" width="60">
                  <template #default="{ $index }">
                    <div class="rank-container">
                      <!-- 动态渲染图片 -->
                      <img
                        v-if="$index < 3"
                        :src="`/${['第一名', '第二名', '第三名'][$index]}.png`"
                        :alt="`第${$index + 1}名`"
                        class="rank-icon"
                      />
                      <!-- 非前三名显示文字 -->
                      <span v-else>{{ `第${$index + 1}名` }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="项目名称" prop="name">
                  <template #default="{ row }">
                    <span class="rank-name" :title="row.name">{{ row.name }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="采收率" prop="value" width="80" align="right">
                  <template #default="{ row }">
                    <span class="rank-value">{{ row.value }}%</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
              <p class="no-data">暂无数据</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="never">
            <template #header>
              <div class="flex-x-between">
                <span class="text-gray">天然气采收率</span>
              </div>
            </template>
            <div v-if="trqList.length > 0">
              <el-table :data="trqList" style="width: 100%" :show-header="false">
                <el-table-column label="排名" width="60">
                  <template #default="{ $index }">
                    <div class="rank-container">
                      <!-- 动态渲染图片 -->
                      <img
                        v-if="$index < 3"
                        :src="`/${['第一名', '第二名', '第三名'][$index]}.png`"
                        :alt="`第${$index + 1}名`"
                        class="rank-icon"
                      />
                      <!-- 非前三名显示文字 -->
                      <span v-else>{{ `第${$index + 1}名` }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="项目名称" prop="name">
                  <template #default="{ row }">
                    <span class="rank-name" :title="row.name">{{ row.name }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="采收率" prop="value" width="80" align="right">
                  <template #default="{ row }">
                    <span class="rank-value">{{ row.value }}%</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
              <p class="no-data">暂无数据</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="never">
            <template #header>
              <div class="flex-x-between">
                <span class="text-gray">米钻井成本</span>
              </div>
            </template>
            <div v-if="mzjList.length > 0">
              <el-table :data="mzjList" style="width: 100%" :show-header="false">
                <el-table-column label="排名" width="60">
                  <template #default="{ $index }">
                    <div class="rank-container">
                      <!-- 动态渲染图片 -->
                      <img
                        v-if="$index < 3"
                        :src="`/${['第一名', '第二名', '第三名'][$index]}.png`"
                        :alt="`第${$index + 1}名`"
                        class="rank-icon"
                      />
                      <!-- 非前三名显示文字 -->
                      <span v-else>{{ `第${$index + 1}名` }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="项目名称" prop="name">
                  <template #default="{ row }">
                    <span class="rank-name" :title="row.name">{{ row.name }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="采收率" prop="value" width="120" align="right">
                  <template #default="{ row }">
                    <span class="rank-value">{{ row.value }}万元/米</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
              <p class="no-data">暂无数据</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" class="warning-module-card mt-5">
      <div slot="header" class="flex-x-between">
        <span class="module-title">统计模块</span>
      </div>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-card shadow="never">
            <div ref="capacityChart" style="width: 100%; height: 250px"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <div ref="investmentChart" style="width: 100%; height: 250px"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import SysYouqitouziAPI, { SysDashboardForm, SysYouqitouziPageQuery } from "@/api/system/sys-youqitouzi";

// eslint-disable-next-line no-undef
const queryFormRef = ref(ElForm);
const queryParams = reactive<SysYouqitouziPageQuery>(<SysYouqitouziPageQuery>{});
const loading = ref(false);

const yyList = ref<SysDashboardForm[]>([]);
const trqList = ref<SysDashboardForm[]>([]);
const mzjList = ref<SysDashboardForm[]>([]);
const gfcnList = ref<SysDashboardForm[]>([]);
const ztzList = ref<SysDashboardForm[]>([]);

const capacityChart = ref(null);
const investmentChart = ref(null);
const capacityChartInstance = ref<any>(null);
const investmentChartInstance = ref<any>(null);

let recordDates = ref<[string, string]>([getToday(), getToday()]);

const initCapacityChart = () => {
  const chartDom = capacityChart.value;
  if (!chartDom) return;

  // 如果已存在实例，先清理
  if (capacityChartInstance.value) {
    capacityChartInstance.value.dispose(); // 销毁老实例
  }

  // 创建新实例
  capacityChartInstance.value = echarts.init(chartDom);

  const option = {
    title: { text: "高峰产能", left: "center" },
    tooltip: {
      trigger: "item",
      formatter: "{b} : 数量: {c} 占比: {d}%",
    },
    legend: { orient: "vertical", left: "left" },
    series: [
      {
        name: "高峰产能",
        type: "pie",
        radius: "50%",
        data: gfcnList.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  capacityChartInstance.value.setOption(option);
};

const initInvestmentChart = () => {
  const chartDom = investmentChart.value;
  if (!chartDom) return;

  // 如果已存在实例，先清理
  if (investmentChartInstance.value) {
    investmentChartInstance.value.dispose();
  }

  // 创建新实例
  investmentChartInstance.value = echarts.init(chartDom);

  const option = {
    title: { text: "总投资", left: "center" },
    tooltip: {
      trigger: "item",
      formatter: "{b} : 数量: {c} 占比: {d}%",
    },
    legend: { orient: "vertical", left: "left" },
    series: [
      {
        name: "总投资",
        type: "pie",
        radius: "50%",
        data: ztzList.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  investmentChartInstance.value.setOption(option);
};

function handleQuery() {
  loading.value = true;
  SysYouqitouziAPI.dashboard(queryParams)
    .then((data) => {
      yyList.value = data.yyList;
      trqList.value = data.trqList;
      mzjList.value = data.mzjList;

      // 更新图表数据
      gfcnList.value = data.gfcnList;
      ztzList.value = data.ztzList;

      // 重新渲染图表
      initCapacityChart();
      initInvestmentChart();
    })
    .finally(() => {
      loading.value = false;
    });
}

function getToday() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function handleResetQuery() {
  queryFormRef.value!.resetFields();
  recordDates.value = [getToday(), getToday()];
  queryParams.createTime = recordDates.value;
  handleQuery();
}

onBeforeUnmount(() => {
  if (capacityChartInstance.value) {
    capacityChartInstance.value.dispose();
    capacityChartInstance.value = null;
  }

  if (investmentChartInstance.value) {
    investmentChartInstance.value.dispose();
    investmentChartInstance.value = null;
  }
});
onMounted(() => {
  recordDates.value = [getToday(), getToday()];
  queryParams.createTime = recordDates.value;
  handleQuery();
});
</script>

<style lang="scss" scoped>
.el-table {
  font-size: 14px;

  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .rank-name {
    min-width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .rank-value {
    font-weight: bold;
  }

  .first {
    color: #f8961e; // 金牌色
  }

  .second {
    color: #f9844a; // 银牌色
  }

  .third {
    color: #f9c74f; // 铜牌色
  }
}

.el-card__header .text-gray {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.dashboard-container {
  position: relative;
  padding: 15px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }

    &:hover {
      transform: translateX(5px);
    }

    .version-content {
      margin-bottom: 12px;
      font-size: 13px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }
}

.warning-module-card {
  .module-title {
    margin-bottom: 10px;
    margin-left: 10px;
    font-size: 28px;
    font-weight: bold;
    color: var(--el-text-color-regular);
  }
}

.no-data {
  text-align: center;
  color: #999;
  font-size: 20px;
  padding: 26px 0;
}

.rank-container {
  display: flex;
  align-items: center;
}

.rank-icon {
  width: 24px; /* 调整图片大小 */
  height: 24px;
  margin-right: 5px;
}
</style>
